package org.nyt.medicalstore.controller;

import org.nyt.medicalstore.model.Prescription;
import org.nyt.medicalstore.service.PrescriptionService;
import org.nyt.medicalstore.dto.PrescriptionDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/prescriptions")
public class PrescriptionController {
    @Autowired
    private PrescriptionService prescriptionService;

    private PrescriptionDTO toDTO(Prescription prescription) {
        if (prescription == null) return null;
        PrescriptionDTO dto = new PrescriptionDTO();
        dto.setId(prescription.getId());
        dto.setCustomerId(prescription.getCustomer() != null ? prescription.getCustomer().getId() : null);
        dto.setDrugId(prescription.getDrug() != null ? prescription.getDrug().getId() : null);
        dto.setDoctor(prescription.getDoctor());
        dto.setRegisterDate(prescription.getRegisterDate());
        dto.setApproved(prescription.getApproved());
        return dto;
    }

    @PostMapping
    public PrescriptionDTO addPrescription(@RequestBody Prescription prescription) {
        return toDTO(prescriptionService.savePrescription(prescription));
    }

    @GetMapping("/{id}")
    public PrescriptionDTO getPrescription(@PathVariable Long id) {
        return toDTO(prescriptionService.getPrescriptionById(id));
    }

    @GetMapping
    public List<PrescriptionDTO> getAllPrescriptions() {
        return prescriptionService.getAllPrescriptions().stream().map(this::toDTO).collect(Collectors.toList());
    }

    @DeleteMapping("/{id}")
    public void deletePrescription(@PathVariable Long id) {
        prescriptionService.deletePrescription(id);
    }
} 